<template>
  <div class="category-container">
    <el-card class="box-card">
      <!-- 添加分类按钮 -->
      <el-button type="primary" :icon="Plus" @click="addCategory">添加分类</el-button>

      <!-- 表格 -->
      <el-table :data="categoryList" border style="margin: 10px 0px">
        <el-table-column label="序号" type="index" align="center" width="80"/>
        <el-table-column label="分类名称" prop="categoryName"/>
        <el-table-column label="创建时间" prop="createTime" align="center"/>
        <el-table-column label="更新时间" prop="updateTime" align="center"/>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" @click="updateCategory(row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" @click="removeCategory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="prev, pager, next, jumper, -> , sizes, total"
          :total="total"
          @current-change="getCategory"
          @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 添加与修改分类的对话框 -->
    <el-dialog v-model="dialogVisible" :title="categoryId ? '修改分类' : '添加分类'">
      <el-form :model="categoryForm" :rules="rules" ref="formRef">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {Plus, Edit, Delete} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import type {FormInstance} from 'element-plus'
import {reqCategoryList, reqAddCategory, reqUpdateCategory, reqDeleteCategory} from '@/apis/category'
import type {CategoryData} from '@/apis/category/type'

// 分页相关数据
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let categoryList = ref<CategoryData[]>([])

// 对话框相关数据
let dialogVisible = ref<boolean>(false)
let categoryId = ref<number>()
let categoryForm = ref({
  categoryName: ''
})
let formRef = ref<FormInstance>()

// 表单验证规则
const rules = {
  categoryName: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 10, message: '分类名称长度在2-10个字符之间', trigger: 'blur'}
  ]
}

// 获取分类列表数据
const getCategory = async (pager = 1) => {
  pageNo.value = pager
  const result = await reqCategoryList({
    page: pageNo.value,
    size: pageSize.value
  })
  if (result.code === 200) {
    categoryList.value = result.data.records
    total.value = result.data.total
  }
}

// 添加分类
const addCategory = () => {
  categoryId.value = undefined
  categoryForm.value.categoryName = ''
  dialogVisible.value = true
}

// 修改分类
const updateCategory = (row: any) => {
  categoryId.value = row.id
  categoryForm.value.categoryName = row.categoryName
  dialogVisible.value = true
}

// 保存分类
const save = async () => {
  // 表单验证
  await formRef.value?.validate()

  try {
    if (categoryId.value) {
      // 修改
      await reqUpdateCategory(categoryId.value, categoryForm.value)
      ElMessage.success('修改成功')
    } else {
      // 添加
      await reqAddCategory(categoryForm.value)
      ElMessage.success('添加成功')
    }
    // 刷新列表
    await getCategory()
    // 关闭对话框
    dialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除分类
const removeCategory = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      type: 'warning'
    })
    await reqDeleteCategory(row.id)
    ElMessage.success('删除成功')
    await getCategory(categoryList.value.length === 1 ? pageNo.value - 1 : pageNo.value)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 页码大小改变
const handleSizeChange = () => {
  getCategory()
}

onMounted(() => {
  getCategory()
})
</script>

<style scoped lang="scss">
.category-container {
  .box-card {
    margin: 10px;
  }
}
</style> 